package com.example.demo.service;

import com.example.demo.converter.MessageConverter;
import com.example.demo.dao.Message;
import com.example.demo.dao.MessageRepository;
import com.example.demo.dto.MessageDTO;
import com.example.demo.dto.UserDTO;
import com.example.demo.dto.UserDetailDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    MessageRepository messageRepository;
    @Autowired
    UserService userService;
    @Autowired
    private UserDetailService userDetailService;
    @Override
    public Long sendMessageByUserIdAndReceiverId(MessageDTO messageDTO,long userId,long receiverId) {
        UserDTO sender = userService.getUserById(userId);
        UserDTO receiver=userService.getUserById(receiverId);
        messageDTO.setSender(sender);
        messageDTO.setReceiver(receiver);
        Message message=messageRepository.save(MessageConverter.convertMessage(messageDTO));
        return message.getId();
    }
    @Override
    public void deleteMessageByMessageId(long messageId) {
        messageRepository.deleteById(messageId);
    }

    @Override
    public Set<MessageDTO> getMessageBySenderIdAndReceiverId(long userId, long receiverId) {
        return MessageConverter.convertToMessageDTOSet(messageRepository.findBySenderIdAndReceiverId(userId,receiverId));
    }

    @Override
    public Set<MessageDTO> getLatestMessagesBySenderId(Long senderId) {
        Set<MessageDTO> messageDTOS=MessageConverter.convertToMessageDTOSet(messageRepository.findLatestMessagesBySenderId(senderId));
        for(MessageDTO messageDTO :messageDTOS){
            UserDTO receiverDTO=messageDTO.getReceiver();
            UserDTO senderDTO=messageDTO.getSender();
            UserDetailDTO receiverDetailDTO= userDetailService.getUserDetailByUserId(receiverDTO.getId());
            UserDetailDTO senderDTODetailDTO= userDetailService.getUserDetailByUserId(senderDTO.getId());
            receiverDTO.setUserDetailDTO(receiverDetailDTO);
            senderDTO.setUserDetailDTO(senderDTODetailDTO);
            messageDTO.setReceiver(receiverDTO);
            messageDTO.setSender(senderDTO);
        }
        return messageDTOS;
    }
}
